<template>
  <view class="container">
    <view class="header">
      <text class="title">设备测试页面</text>
      <text class="subtitle">用于验证节拍器功能是否正常工作</text>
    </view>
    
    <view class="debug-info">
      <text class="debug-item">音频源: {{ audioSourceMode }}</text>
      <text class="debug-item">本地文件支持: {{ localFileSupport }}</text>
      <text class="debug-item">平台: {{ platform }}</text>
    </view>
    
    <!-- 木鱼声专用测试 -->
    <view class="debug-section">
      <text class="section-title">木鱼声专用测试</text>
      
      <view class="base64-test">
        <button @tap="testBase64Audio" class="base64-btn">测试Base64音频</button>
      </view>
      
      <view class="path-test-container">
        <view class="path-test-item" v-for="(path, index) in testPaths" :key="index">
          <text class="path-text">{{ path }}</text>
          <button @tap="testSpecificPath(path)" class="path-test-btn">测试</button>
          <text v-if="pathResults[path]" :class="['status', {'success': pathResults[path].success}]">
            {{ pathResults[path].message }}
          </text>
        </view>
      </view>
    </view>
    
    <view class="debug-section">
      <text class="section-title">音频测试</text>
      <view class="sound-grid">
        <view v-for="(sound, index) in soundTypes" :key="index" class="sound-card">
          <text class="sound-name">{{ sound.name }}</text>
          <text class="sound-path">{{ sound.accent }}</text>
          <view class="buttons">
            <button @tap="testSound(index, true)" class="test-btn accent">强拍</button>
            <button @tap="testSound(index, false)" class="test-btn">弱拍</button>
          </view>
          <text v-if="soundStatus[index]" :class="['status', {'success': soundStatus[index].success}]">
            {{ soundStatus[index].message }}
          </text>
        </view>
      </view>
      
      <view class="audio-controls">
        <button @tap="forceLocalFiles" class="mode-btn" :class="{'active': !useBase64}">强制使用本地文件</button>
        <button @tap="forceBase64" class="mode-btn" :class="{'active': useBase64}">强制使用Base64</button>
      </view>
    </view>
    
    <view class="debug-section">
      <text class="section-title">振动功能测试</text>
      <view class="vibration-buttons">
        <button @tap="testShortVibration" class="test-btn">测试短振动</button>
        <button @tap="testLongVibration" class="test-btn accent">测试长振动</button>
      </view>
      <text v-if="vibrationStatus" :class="['status', {'success': vibrationStatus.success}]">
        {{ vibrationStatus.message }}
      </text>
    </view>
    
    <view class="debug-section">
      <text class="section-title">节拍器测试</text>
      <view class="metronome-controls">
        <picker @change="changeBeats" :value="beatsIndex" :range="beatsOptions">
          <view class="picker-item">
            <text>拍数: {{ beatsOptions[beatsIndex] }}</text>
          </view>
        </picker>
        
        <slider 
          :value="tempo" 
          :min="60" 
          :max="180" 
          :step="1" 
          show-value 
          @change="changeTempo"
        />
        
        <button @tap="toggleMetronome" class="test-btn" :class="{'accent': isPlaying}">
          {{ isPlaying ? '停止' : '开始' }}
        </button>
      </view>
    </view>
    
    <view class="footer">
      <button @tap="goBack" class="back-btn">返回主页</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
import metronomeService from '../../utils/metronomeService.js';

// 测试状态
const vibrationStatus = ref(null);
const soundStatus = reactive({});
const isPlaying = ref(false);
const tempo = ref(100);
const beatsOptions = ref(['2', '3', '4', '5', '6']);
const beatsIndex = ref(2); // 默认选择4拍
const soundTypes = ref(metronomeService.soundTypes);

// 额外的状态
const useBase64 = ref(metronomeService.useBase64Fallback);
const audioSourceMode = computed(() => useBase64.value ? 'Base64编码' : '本地文件');
const localFileSupport = ref('检测中...');

// 平台信息
const platform = ref('');

// 木鱼声专用测试
const testPaths = ref([
  '/static/sounds/woodblock_accent.mp3',
  '/static/sounds/woodblock_normal.mp3',
  'static/sounds/woodblock_accent.mp3',
  '/woodblock_accent.mp3',
  '../../../static/sounds/woodblock_accent.mp3'
]);
const pathResults = reactive({});

// 检测本地文件支持情况
function checkLocalFileSupport() {
  try {
    const audio = uni.createInnerAudioContext();
    audio.src = 'static/sounds/woodblock_accent.mp3';
    
    audio.onCanplay(() => {
      localFileSupport.value = '支持';
      audio.destroy();
    });
    
    audio.onError((err) => {
      localFileSupport.value = `不支持 (${err.errMsg || '未知错误'})`;
      audio.destroy();
    });
  } catch (error) {
    localFileSupport.value = `检测错误: ${error.message || '未知错误'}`;
  }
}

// 强制使用本地文件
function forceLocalFiles() {
  metronomeService.useBase64Fallback = false;
  useBase64.value = false;
}

// 强制使用Base64
function forceBase64() {
  metronomeService.useBase64Fallback = true;
  useBase64.value = true;
}

// 测试声音
function testSound(soundIndex, isAccent) {
  try {
    soundStatus[soundIndex] = { success: null, message: '尝试播放中...' };
    
    // 获取当前音频源
    const mode = useBase64.value ? 'Base64' : '本地文件';
    
    // 使用metronomeService测试音频
    const result = metronomeService.testAudio(soundIndex, isAccent);
    
    if (result) {
      soundStatus[soundIndex] = { 
        success: true, 
        message: `${isAccent ? '强拍' : '弱拍'}音频播放成功! (${mode})` 
      };
    } else {
      soundStatus[soundIndex] = { 
        success: false, 
        message: `${isAccent ? '强拍' : '弱拍'}音频播放失败! (${mode})` 
      };
    }
  } catch (error) {
    soundStatus[soundIndex] = { 
      success: false, 
      message: `错误: ${error.message || '未知错误'}` 
    };
    console.error('测试音频时发生异常:', error);
  }
}

// 测试短振动
function testShortVibration() {
  try {
    vibrationStatus.value = { success: null, message: '尝试短振动...' };
    
    uni.vibrateShort({
      success: () => {
        vibrationStatus.value = { success: true, message: '短振动成功!' };
        console.log('短振动成功');
      },
      fail: (err) => {
        vibrationStatus.value = { success: false, message: `短振动失败: ${err.errMsg || '未知错误'}` };
        console.error('短振动失败:', err);
      }
    });
  } catch (error) {
    vibrationStatus.value = { success: false, message: `错误: ${error.message || '未知错误'}` };
    console.error('测试振动时发生异常:', error);
  }
}

// 测试长振动
function testLongVibration() {
  try {
    vibrationStatus.value = { success: null, message: '尝试长振动...' };
    
    uni.vibrateLong({
      success: () => {
        vibrationStatus.value = { success: true, message: '长振动成功!' };
        console.log('长振动成功');
      },
      fail: (err) => {
        vibrationStatus.value = { success: false, message: `长振动失败: ${err.errMsg || '未知错误'}` };
        console.error('长振动失败:', err);
      }
    });
  } catch (error) {
    vibrationStatus.value = { success: false, message: `错误: ${error.message || '未知错误'}` };
    console.error('测试振动时发生异常:', error);
  }
}

// 修改节拍器拍数
function changeBeats(e) {
  beatsIndex.value = e.detail.value;
  const beats = parseInt(beatsOptions.value[beatsIndex.value]);
  metronomeService.setTimeSignature(beats);
}

// 修改节拍器速度
function changeTempo(e) {
  tempo.value = e.detail.value;
  metronomeService.setTempo(tempo.value);
}

// 开始或停止节拍器
function toggleMetronome() {
  if (isPlaying.value) {
    metronomeService.stop();
  } else {
    metronomeService.start();
  }
  isPlaying.value = metronomeService.isPlaying;
}

// 测试特定路径
function testSpecificPath(path) {
  try {
    pathResults[path] = { success: null, message: '尝试播放中...' };
    
    const audio = uni.createInnerAudioContext();
    audio.src = path;
    
    console.log(`测试特定路径: ${path}`);
    
    audio.onPlay(() => {
      console.log(`路径 ${path} 开始播放`);
    });
    
    audio.onCanplay(() => {
      pathResults[path] = { success: true, message: '音频可以播放!' };
      console.log(`路径 ${path} 可以播放`);
    });
    
    audio.onError((err) => {
      pathResults[path] = { 
        success: false, 
        message: `错误: ${err.errMsg || '未知错误'} (${err.errCode || '未知代码'})` 
      };
      console.error(`路径 ${path} 播放失败:`, err);
    });
    
    audio.play();
  } catch (error) {
    pathResults[path] = { 
      success: false, 
      message: `异常: ${error.message || '未知错误'}` 
    };
    console.error(`测试路径时发生异常:`, error);
  }
}

// 返回主页
function goBack() {
  uni.switchTab({
    url: '/pages/index/index'
  });
}

// 页面创建时初始化
onMounted(() => {
  // 获取平台信息
  try {
    const systemInfo = uni.getSystemInfoSync();
    platform.value = systemInfo.platform || '未知';
  } catch (e) {
    platform.value = '获取失败';
  }
  
  // 检测本地文件支持
  checkLocalFileSupport();
  
  // 更新状态
  useBase64.value = metronomeService.useBase64Fallback;
  
  // 设置回调
  metronomeService.setOnBeatCallback((beat, isAccent) => {
    console.log(`当前拍: ${beat}, 是否是强拍: ${isAccent}`);
  });
});

// 页面卸载时停止节拍器
onUnmounted(() => {
  if (metronomeService.isPlaying) {
    metronomeService.stop();
  }
});

// Base64测试
function testBase64Audio() {
  try {
    const audio = uni.createInnerAudioContext();
    // 直接使用Base64音频
    audio.src = metronomeService.soundTypes[1].accentBase64;
    
    console.log('测试Base64音频');
    
    audio.onPlay(() => {
      console.log('Base64音频开始播放');
    });
    
    audio.onCanplay(() => {
      uni.showToast({
        title: 'Base64音频可以播放!',
        icon: 'success'
      });
      console.log('Base64音频可以播放');
    });
    
    audio.onError((err) => {
      uni.showToast({
        title: 'Base64音频播放失败',
        icon: 'error'
      });
      console.error('Base64音频播放失败:', err);
    });
    
    audio.play();
  } catch (error) {
    console.error('测试Base64音频时发生异常:', error);
  }
}
</script>

<style>
.container {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  height: 100vh;
  box-sizing: border-box;
}

.header {
  margin-bottom: 30rpx;
  text-align: center;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 28rpx;
  color: #666;
}

.debug-info {
  background-color: #f0f0f0;
  padding: 15rpx;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
  font-family: monospace;
}

.debug-item {
  display: block;
  font-size: 24rpx;
  margin-bottom: 5rpx;
}

.sound-path {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
  font-family: monospace;
}

.debug-section {
  margin-bottom: 30rpx;
  background-color: #f8f8f8;
  padding: 20rpx;
  border-radius: 10rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.sound-grid {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.sound-card {
  background-color: #ffffff;
  border-radius: 10rpx;
  padding: 15rpx;
  display: flex;
  flex-direction: column;
}

.sound-name {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.buttons {
  display: flex;
  gap: 20rpx;
  margin-bottom: 10rpx;
}

.test-btn {
  flex: 1;
  font-size: 28rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #e0e0e0;
}

.test-btn.accent {
  background-color: #007AFF;
  color: white;
}

.status {
  font-size: 28rpx;
  color: #ff3b30;
  margin-top: 10rpx;
  text-align: center;
}

.status.success {
  color: #34c759;
}

.vibration-buttons {
  display: flex;
  gap: 20rpx;
  margin-bottom: 15rpx;
}

.metronome-controls {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.picker-item {
  background-color: #ffffff;
  padding: 15rpx;
  border-radius: 8rpx;
  text-align: center;
}

.footer {
  margin-top: auto;
  padding: 20rpx 0;
}

.back-btn {
  background-color: #007AFF;
  color: white;
}

.audio-controls {
  margin-top: 20rpx;
  display: flex;
  justify-content: space-between;
}

.mode-btn {
  flex: 1;
  margin: 0 10rpx;
  font-size: 26rpx;
  background-color: #e0e0e0;
}

.mode-btn.active {
  background-color: #007AFF;
  color: white;
}

.path-test-container {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
  margin-bottom: 20rpx;
}

.path-test-item {
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  padding: 15rpx;
  border-radius: 8rpx;
}

.path-text {
  font-family: monospace;
  font-size: 24rpx;
  margin-bottom: 10rpx;
  word-break: break-all;
}

.path-test-btn {
  align-self: flex-end;
  font-size: 24rpx;
  height: 60rpx;
  line-height: 60rpx;
  padding: 0 20rpx;
  background-color: #007AFF;
  color: white;
}

.base64-test {
  margin-bottom: 20rpx;
}

.base64-btn {
  background-color: #007AFF;
  color: white;
}
</style> 